package com.region.spring.annotation;

import com.region.spring.client.RegionConfigurer;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;


/**
 * @author liujieyu
 * @date 2024/7/17 17:05
 * @desciption
 */
public class RegionConfigurerRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes mapperScanAttrs = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(RegionAdapterSpring.class.getName()));
        if (mapperScanAttrs != null) {
            registerBeanDefinitions(mapperScanAttrs, registry, generateBaseBeanName(importingClassMetadata, 0));
        }
    }

    private void registerBeanDefinitions(AnnotationAttributes attributes, BeanDefinitionRegistry registry, String beanName) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RegionConfigurer.class);

        String factoryBeanRef = attributes.getString("factoryBeanRef");
        if (StringUtils.hasText(factoryBeanRef)) {
            builder.addPropertyValue("factoryBeanReferenceName", factoryBeanRef);
        }
        String[] packages = attributes.getStringArray("value");
        if (packages != null && packages.length != 0) {
            builder.addPropertyValue("basePackages", packages);
        }
        builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

        registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
    }

    private String generateBaseBeanName(AnnotationMetadata importingClassMetadata, int index) {
        return importingClassMetadata.getClassName() + "#" + RegionConfigurerRegistrar.class.getSimpleName() + "#" + index;
    }
}
